package hhtc.jsjds.controller;


import com.alibaba.fastjson.JSON;
import hhtc.jsjds.constant.Constants;
import hhtc.jsjds.constant.RedisKey;
import hhtc.jsjds.entity.VerifyCode;
import hhtc.jsjds.enums.StatusCodeEnum;
import hhtc.jsjds.exception.XscoderException;
import hhtc.jsjds.redis.RedisProvider;
import hhtc.jsjds.service.CommonService;
import hhtc.jsjds.service.StudentService;
import hhtc.jsjds.utils.*;
import hhtc.jsjds.vo.Result;
import hhtc.jsjds.vo.UserRegisterVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {


    @Value("${vcode.verifiesUrl}")
    private String verifiesUrl;

    @Autowired
    CommonService commonService;

    @Autowired
    StudentService studentService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisProvider redisProvider;

    @GetMapping("/vcode")
    public void getVcode(HttpServletRequest request, HttpServletResponse response, String stu_num) throws IOException {
        if (StringUtils.isBlank(stu_num)) {
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        String ip = IpUtil.getIpAddrByRequest(request);
        if (stringRedisTemplate.opsForValue().get("FREQUENCY_VCODE:" + ip) == null) {
            stringRedisTemplate.opsForValue().set("FREQUENCY_VCODE:" + ip, "1", 10, TimeUnit.MINUTES);
        } else {
            if(Integer.parseInt(stringRedisTemplate.opsForValue().get("FREQUENCY_VCODE:"+ip)+"")>100){
                throw new XscoderException(StatusCodeEnum.OPT_TOO_FAST);
            }
        }
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/gif");

        int rand = new Random().nextInt(300);
        VerifyCode verifyCode = new VerifyCode();
        verifyCode.setFile_name(rand+"");
        verifyCode = commonService.getVerifyCode(verifyCode);
        stringRedisTemplate.opsForValue().set("REGIST_VCODE:"+stu_num+ip,verifyCode.getCode(),5, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().increment("FREQUENCY_VCODE:"+ip,1);
        FileInputStream fis = new FileInputStream(new File(verifiesUrl + verifyCode.getFile_name()+".png"));
        int size =fis.available();
        byte data[]=new byte[size];
        fis.read(data);
        OutputStream os = response.getOutputStream();
        os.write(data);
        os.flush();
        os.close();
    }

    @PostMapping("/user")
    public Result newUser(HttpServletRequest request, @RequestBody UserRegisterVO userRegisterVO) {

        if (userRegisterVO.getUsername().length() != 10) {
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        if (userRegisterVO.getUsername().contains("HHTC")) {
            throw new XscoderException(StatusCodeEnum.REGIST_NOT_ALLOWED);
        }

        String redisKey = RedisKey.VERIFICATION + userRegisterVO.getUsername() + ":" + userRegisterVO.getPhone();
        String code = redisProvider.get(redisKey);
//        if (!userRegisterVO.getVcode().equals(code)) {
//            throw new XscoderException(StatusCodeEnum.WRONG_VCODE);
//        }
        Boolean flag = studentService.InsertNewStudent(userRegisterVO.getUsername(), userRegisterVO.getPassword());
        return new Result(flag, StatusCodeEnum.OK);
    }

}
